﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Routine.Api.Entities;
using Routine.Api.Models;
using Routine.Api.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Routine.Api.Controllers
{
    [ApiController]
    [Route("api/companycollections")]//一次性的加入多个集合，要单独写一个类：
    public class CompanyCollectionsControlle : ControllerBase//通过他来一次性加入一组数据。
    {
        private readonly IMapper _mapper;
        private readonly ICompanyRepository _companyRepository;

        public CompanyCollectionsControlle(IMapper mapper, ICompanyRepository companyRepository)
        {
            _mapper = mapper ?? throw new ArgumentNullException();
            _companyRepository = companyRepository ?? throw new ArgumentNullException();
        }

        //[HttpGet("{ids}",Name =nameof(GetCompanyCollection))]
        //public async Task<IActionResult> GetCompanyCollection(
        //    [FromRoute]              //因为get里面默认不包含body，所有要写上【fromBody】
        //    [ModelBinder(BinderType =typeof(ArrayModelBinder))]
        //    IEnumerable<Guid>ids)
        //{
        //    if (ids==null)
        //    {
        //        return BadRequest();
        //    }
        //    var entities = await _companyRepository.GetCompaniesAsync(ids);

        //    if (ids.Count()!=entities.Count())
        //    {
        //        return NotFound();
        //    }
        //    var dtosToReturn = _mapper.Map<IEnumerable<CompanyDto>>(entities);
        //    return Ok(dtosToReturn);
        //}

        [HttpPost]
        public async Task<ActionResult<IEnumerable<CompanyDto>>> CreateCompanyCollection
            (IEnumerable<CompanyAddDto> companycollection)//运行起来以后，把鼠标放上去，可以直接看变量的数据
        {
            var companyEntities = _mapper.Map<IEnumerable<Company>>(companycollection);

            foreach (var company in companyEntities)
            {
                _companyRepository.AddCompany(company);
            }

            await _companyRepository.SaveAsync();
            var dtosToReturn = _mapper.Map<IEnumerable<CompanyDto>>(companyEntities);
            var idsString = string.Join(",",dtosToReturn.Select(x => x.Id));

           return Ok();       //可以用返回OK表示200，先检查一下；

          //  return CreatedAtRoute(nameof(GetCompanyCollection),new { ids=idsString},dtosToReturn);//中间缺少的是ids的参数
        }
        //传入的json文件，如果是个数组，要使用【】括起来；
    }
}
